<?php
namespace App\Services\Game;
use App\DTOS\Admin\ActiveRuleSearchDTO;
use App\DTOS\Admin\AlarmSearchDTO;
use App\Models\ActiveRule;
use App\Models\ActiveRuleQd;
use App\Models\Game\Alarm;
use App\Models\Game\Server;
use App\Models\Game\UserRole;


class AlarmService
{
    /**
    * @var  \Illuminate\Database\Eloquent\Builder
    */


    public function paginate(AlarmSearchDTO $DTO)
    {
        $model = Alarm::query();

        $perPage = $DTO->getLimit();
        $page = $DTO->getPage();
        $createDateTimeBegin = $DTO->getCreateDateTimeBegin();
        $createDateTimeEnd = $DTO->getCreateDateTimeEnd();
        $roleId = $DTO->getRoleId();
        $gameArea = $DTO->getGameArea();

        // 初始化查询构建器
        $query = $model
            ->select(
                'alarm',
                \DB::raw('FROM_UNIXTIME(logTime, "%Y-%m-%d %H:%i:%s") AS formattedLogTime'),
                \DB::raw('GROUP_CONCAT(DISTINCT roleId SEPARATOR "|") AS roleIds'),
                \DB::raw('GROUP_CONCAT(DISTINCT nick SEPARATOR "|") AS nicks'),
                \DB::raw('COUNT(*) AS total')
            )
            ->groupBy('alarm', 'formattedLogTime'); // 按 alarm 和格式化的 logTime 分组

        // 添加时间范围条件
        if ($createDateTimeBegin) {
            $timestampBegin = strtotime($createDateTimeBegin);
            $query->where("logTime", ">=", $timestampBegin);
        }
        if ($createDateTimeEnd) {
            $timestampEnd = strtotime($createDateTimeEnd);
            $query->where("logTime", "<=", $timestampEnd);
        }

        // 添加 roleId 条件
        if ($roleId) {
            $query->where("roleId", $roleId);
        }



        // 按总数降序排序
        $query->orderBy('total', 'desc');

        // 返回分页结果
        return $query->paginate($perPage, ['*'], 'page', $page);
    }


}
